package org.common.convert.util;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class HtmlImageToDataUri {

    public static void main(String[] args) throws IOException {
        String htmlFilePath = "D:\\temp\\新建文件夹\\新建文件夹\\zxxx.htm";  // 输入的HTML文件路径
        String outputFilePath = "D:\\temp\\新建文件夹\\新建文件夹\\zxxx.html"; // 输出的HTML文件路径
        convertImgToDataUri(htmlFilePath, outputFilePath);
        //修复html文件中的编码问题
        HtmlCharsetFixer.fixCharsetMeta(outputFilePath, outputFilePath);
    }

    public static void convertImgToDataUri(String htmlFilePath, String outputFilePath) {
        try {
            // 1. 读取HTML文件
            Path path = Paths.get(htmlFilePath);
            String htmlContent = FileHelper.readFileByCharset (htmlFilePath,"GB2312");
            Document doc = Jsoup.parse(htmlContent);

            // 2. 处理所有<img>标签
            Elements imgs = doc.select("img");
            for (Element img : imgs) {
                String src = img.attr("src");
                if (src == null || src.isEmpty()) {
                    continue;
                }

                // 3. 获取图片的绝对路径（假设相对HTML文件所在目录）
                //Path imgPath = Paths.get(path.getParent().toString(), src);
                Path imgPath = path.resolveSibling(src);
                try {
                    // 4. 读取图片并转为Base64
                    byte[] imgBytes = Files.readAllBytes(imgPath);
                    String base64Data = Base64.getEncoder().encodeToString(imgBytes);

                    // 5. 获取图片MIME类型（根据文件扩展名）
                    String mimeType = getMimeType(imgPath.toString());

                    // 6. 替换src为Data URI
                    img.attr("src", "data:" + mimeType + ";base64," + base64Data);
                    //删除图片
                    System.out.println("删除图片：" + imgPath.toString());
                    FileHelper.deleteFile(imgPath.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    System.err.println("处理图片失败: " + src + ", 错误: " + e.getMessage());
                }
            }

            // 7. 保存修改后的HTML
            FileHelper.writeString(Paths.get(outputFilePath), doc.outerHtml());
            System.out.println("处理完成，输出文件: " + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 根据文件扩展名获取MIME类型
    private static String getMimeType(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "png":
                return "image/png";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "gif":
                return "image/gif";
            case "webp":
                return "image/webp";
            case "svg":
                return "image/svg+xml";
            default:
                return "application/octet-stream"; // 默认二进制流
        }
    }
}
